<!-- Author: Edwin -->
<template>
  <el-row :gutter="15" class="page-content">
    <el-col :span="4">
      <div class="content list">
        <div class="list-title">API List</div>
        <div class="list-tree hide-scroll-bar">
          <el-tree
            :data="apiLists"
            class="tree-lis-api"
            :props="{ children: 'children', label: 'name' }"
            @node-click="clickApiListItem"
          ></el-tree>
        </div>
      </div>
    </el-col>
    <el-col :span="20" class="right-column hide-scroll-bar">
      <el-row :gutter="10" class="mothods-row">
        <el-col :span="12">
          <div>
            <el-form label-width="120px">
              <el-form-item label="Method">
                <el-select v-model="requestInfo.method" disabled>
                  <el-option
                    v-for="item in methodsList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-button
                  @click="requestEvent"
                  :loading="requestBtnLoading"
                  size="small"
                  style="margin-left: 2%"
                  type="primary"
                  >Request</el-button
                >
                <el-button
                  @click="syncData"
                  :loading="syncLoading"
                  size="small"
                  style="margin-left: 2%"
                  type="danger"
                  v-if="syncOpen"
                >
                  Sync data
                </el-button>
              </el-form-item>
              <el-form-item label="Path">
                <el-input v-model="requestInfo.path"></el-input>
              </el-form-item>
              <el-form-item label="API Name">
                <el-input
                  v-model="requestInfo.name"
                  :disabled="true"
                ></el-input>
              </el-form-item>
              <el-form-item label="API doc URL">
                <el-input
                  v-model="requestInfo.apiDoc"
                  :disabled="true"
                ></el-input>
              </el-form-item>
              <el-form-item label="Sync Interval">
                <el-input
                  v-model="requestInfo.syncRate"
                  :disabled="true"
                ></el-input>
              </el-form-item>
              <el-form-item label="Last Sync Date">
                <el-input
                  v-model="requestInfo.lastSyncDate"
                  :disabled="true"
                ></el-input>
              </el-form-item>
              <el-form-item label="parameter">
                <div class="methods-layout">
                  <el-input
                    v-model="requestParams"
                    type="textarea"
                    :rows="8"
                    resize="vertical"
                    placeholder=""
                  ></el-input>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12" class="mothods-row" style="height: 87vh">
          <div class="result-item">
            <div class="result-title">API realtime result</div>
            <v-jsoneditor
              v-model="apiResult"
              v-loading="apiResultLoading"
              class="result-editor"
              :options="jsoneditorSetting.options"
              :plus="jsoneditorSetting.plus"
              :height="jsoneditorSetting.height"
              :indentation="jsoneditorSetting.indentation"
              :search="jsoneditorSetting.search"
              :path="jsoneditorSetting.path"
              :color="jsoneditorSetting.color"
              @error="onError"
            ></v-jsoneditor>
          </div>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import { GlobalTimeformat } from '@/utils/common'
import { syncCustomize } from '@/api/new'
import { parseJSON } from '@/components/storybook/utilties/tools'

export default {
  data() {
    return {
      methodsList: [
        {
          label: 'GET',
          value: 'GET'
        },
        {
          label: 'POST',
          value: 'POST'
        }
        // {
        //   label: 'DELETE',
        //   value: 'DELETE'
        // },
        // {
        //   label: 'PUT',
        //   value: 'PUT'
        // }
      ],
      enableCWbtn: true,
      apiLists: [],
      jsoneditorSetting: {
        options: { mode: 'tree', modes: ['tree', 'code'] },
        plus: false,
        height: '100%',
        indentation: 2,
        search: true,
        color: 'red',
        path: false
      },
      requestBtnLoading: false,
      requestInfo: {
        method: 'get',
        path: null,
        params: null,
        datasetId: null
      },
      // requestMethod: 'get',
      // requestUrl: null,
      requestParams: null,
      paramsDataset: null,
      apiResult: null,
      apiResultLoading: false,
      internalResult: null,
      internalResultLoading: false,

      syncLoading: false,
      syncOpen: false,
      syncClient: undefined,
      syncPath: undefined,
      notifyInstance: null,
      syncMethod: 'GET'
    }
  },
  created() {
    this.getApiListData()
  },
  methods: {
    async syncData() {
      if (!this.syncClient) {
        return this.$message.error('API error.')
      }
      if (!this.syncPath) {
        return this.$message.error('Method error.')
      }

      let params = parseJSON(this.requestParams) || {}
      params.tenantCode = this.$store.state.user.tenantCode
      params.client = this.syncClient
      params.path = this.syncPath
      params.method = this.syncMethod
      try {
        this.syncLoading = true
        this.notifyInstance && this.notifyInstance.close()
        const { data: response } = await syncCustomize(params)
        if (response.code !== 0) {
          this.notifyInstance = this.$notify({
            title: 'Tip',
            message: response.message || response.msg,
            type: 'error',
            offset: 45,
            duration: 0
          })
          return
        }

        this.$message.success(response.message)
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.syncLoading = false
      }
    },
    cwViewEvent() {
      this.$router.push({
        path: '/ConnectWiseTicketView',
        query: { id: this.apiResult[0].id }
      })
      this.$nextTick(() => {
        this.$root.eventBus.$emit('CWbus', this.apiResult[0].id)
      })
    },
    getApiListData() {
      const params = {}
      this.$interface.apiManager
        .getQACheckApiListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.apiLists = res.data
        })
        .catch(() => {})
    },
    requestEvent() {
      if (!this.requestInfo.path) {
        return this.$message.error('API error.')
      }
      if (!this.requestInfo.method) {
        return this.$message.error('Method error.')
      }
      this.requestBtnLoading = true
      this.apiResultLoading = true
      //  this.internalResultLoading = true
      let params = {}

      let startRequest = () => {
        if (this.requestInfo.method === 'GET') {
          try {
            params = JSON.parse(this.requestParams)
          } catch (error) {}
          params['client'] = this.requestInfo.client
          params['path'] = this.requestInfo.path
          return this.$interface.customRequest(
            this.requestInfo.method,
            `/web/dm/client/${this.$store.state.user.tenantCode}/get`,
            params
          )
        } else {
          try {
            params['params'] = JSON.parse(this.requestParams)
          } catch (error) {}
          params['client'] = this.requestInfo.client
          params['path'] = this.requestInfo.path
          return this.$interface.customRequest(
            this.requestInfo.method,
            `/web/dm/client/${this.$store.state.user.tenantCode}/post`,
            params
          )
        }
      }
      startRequest()
        .then(res => {
          this.apiResultLoading = false
          this.apiResult = res.data
        })
        .catch(err => {
          this.$message.error(err.response.data.message)
          this.apiResultLoading = false
          this.apiResult = []
        })
        .finally(() => {
          this.requestBtnLoading = false
        })
      if ( this.apiResultLoading) {
        this.apiResultLoading = false
      }
      // this.getDatasetData(this.requestInfo.datasetId, this.requestInfo.params)
    },
    clickApiListItem(item) {
      this.syncOpen = item.syncOpen
      this.syncPath = item.syncPath
      this.syncMethod = item.method
      this.syncClient = item.syncClient
      if (item.name === 'CW Tickets') {
        this.enableCWbtn = false
      } else {
        this.enableCWbtn = true
      }
      this.requestInfo = Object.assign({}, item)
      this.requestParams = item.params
        ? JSON.stringify(item.params, null, 4)
        : null
      // this.paramsDataset = item.paramsDataset ? JSON.stringify(item.paramsDataset, null, 4) : null
      //   this.paramsDataset = item.paramsDataset
      let params = {
        action: this.requestInfo.action,
        subjectCode: this.requestInfo.subjectCode
      }
      this.$interface.apiManager
        .getLastSyncDate(params)
        .then(({ data: res }) => {
          this.requestInfo.lastSyncDate = GlobalTimeformat(
            res.data.lastSyncDate,
            'HH:mm'
          )
        })
        .catch(() => {})
    },
    getDatasetData(datasetId, params) {
      let requestParams = `filter=${this.paramsDataset}`
      // try {
      //   requestParams = JSON.parse(this.paramsDataset)
      // } catch (error) {
      //   this.internalResultLoading = false
      //   this.internalResult = []
      //   return this.$message.error('Syntax Error')
      // }
      this.$interface.reports
        .getReportDatasetDataApi(datasetId, requestParams)
        .then(({ data: res }) => {
          this.internalResultLoading = false
          if (res.code !== 0) {
            this.internalResult = []
            return this.$message.error(res.msg)
          }
          this.internalResult = res.data
        })
        .catch(() => {
          this.internalResultLoading = false
          this.internalResult = []
        })
    },
    onError(value) {}
  }
}
</script>

<style scoped lang="scss">
@import './index.scss';
// @import "src/views/modules/mspbots/dataset-qa-check/index.scss";
</style>
<style lang="scss">
.tree-lis-api {
  .el-tree-node > .el-tree-node__children {
    overflow: visible !important;
  }
}
</style>
